//
//  UsersController.swift
//  App
//
//  Created by melvyn on 2018/8/18.
//

import Foundation
import Vapor

class UsersController: RouteCollection {
    
    func boot(router: Router) throws {
        
        let noAuth = router.grouped("users")
        
        noAuth.post(use: create)
        noAuth.get(User.Public.parameter, use: find)
        noAuth.get(User.parameter, "lives", use: streams)
        noAuth.get(use: index)
        noAuth.get(User.parameter, "comments", use: comments)
        
        let bearer = noAuth.grouped(User.tokenAuthMiddleware())
        bearer.put(User.parameter, use: update)
        bearer.delete(User.parameter, use: delete)
    }
    
    func create(_ req: Request) throws -> EventLoopFuture<User.Public> {
        return try req.content.decode(User.FormData.self).flatMap({
            return try User.init(formData: $0).create(on: req)
                .map(User.Public.init)
        })
    }
    
    func index(_ req: Request) throws -> EventLoopFuture<[User.Public]> {
        return User.Public.query(on: req).all()
    }
    
    func find(_ req: Request) throws -> EventLoopFuture<User.Public> {
        return try req.parameters.next(User.Public.self)
    }
    
    func update(_ req: Request) throws -> EventLoopFuture<User.Public> {
        return try req.parameters.next(User.self).flatMap { oldValue in
            return try req.content.decode(User.FormData.self).flatMap { newValue in
                return oldValue.update(with: newValue)
                    .save(on: req)
                    .map(User.Public.init)
            }
        }
    }
    
    func delete(_ req: Request) throws -> EventLoopFuture<HTTPStatus> {
        return try req.parameters.next(User.self)
            .delete(on: req)
            .transform(to: .ok)
    }
    
    func streams(_ req: Request) throws -> Future<[LiveStream]> {
        return try req.parameters.next(User.self).flatMap({
            try $0.lives.query(on: req).all()
        })
    }
    
    func comments(_ req: Request) throws -> EventLoopFuture<[Comment]> {
        return try req.parameters.next(User.self).flatMap({
            try $0.comments.query(on: req).all()
        })
    }
}
